
local file = io.open(arg[1],"rb");
local out_file = io.open(arg[2],"wb");
local toMSB = toMSB or false;
assert(file);
assert(out_file);
local data = file:read('*a');
--flash的数据不用翻转
--sram 的数据需要翻转
--实际上应该由jtag脚本来决定是否翻转数据

--[[
len由两个字节组成
 len[15:8] = data[0]
 len[7:0]  = data[1]
]]
local zero_pos = data:find('\x00');
--local pos = 0xf6; --测试
local pos = zero_pos;

local MSB = {};
local _get_bit = function(v,pos)
    return (v>>pos)&1;
end
for i=0,0xff do
    MSB[i] =
        (_get_bit(i,0)<<7)|
        (_get_bit(i,1)<<6)|
        (_get_bit(i,2)<<5)|
        (_get_bit(i,3)<<4)|
        (_get_bit(i,4)<<3)|
        (_get_bit(i,5)<<2)|
        (_get_bit(i,6)<<1)|
        (_get_bit(i,7)<<0) ;
end

--设置地址


local outbin = '';
while(pos<#data)do
    local len = data:byte(pos)<<8;
    len = len + data:byte(pos+1);
    assert((len&0x7)==0,"data error!");
    len = len>>3;
    --print(len);
    pos = pos + 2;
    local s = data:sub(pos,pos+len-1);
    if(toMSB)then
        --转为大端序
        local news = '';
        for k=1,#s do
            news = news .. string.char(MSB[s:byte(k)]);
        end
        s = news;
    end

    outbin = outbin .. s;

    pos = pos + len;
end

-- 每页256字节
out_file:write(outbin);

local dpos = 1;

out512bit = true;

local proc_data_pos = function(ddpos,is512,out_s,end_str)
    if((ddpos%0x100)==0)then
        print(string.format('sflash_program_begin 0x%08x',ddpos));
    end

    if((ddpos%1024)==0)then
        print(string.format('puts "%dKBytes!"',ddpos/1024));
    end

    if(not is512)then
        if((ddpos%0x100)==0xfc)then
            print(string.format('sflash_program_end 0x%08x',end_str));
        else
            print(out_s);
        end
    else
        local pos = ddpos + 64;
        if((pos%0x100)==0)then
            print(string.format('sflash_send512_MSB 0x%s RUN/IDLE',end_str));
        else
            print(out_s);
        end
    end
end

print(string.format('puts "total size:%d KBytes!"',#outbin>>10));

if(out512bit)then
    while((dpos+64)<=#outbin)do
        local s = '';
        for k=0,63,1 do
            local b = outbin:byte(dpos+k);
            b = MSB[b];
            s = string.format('%02x%s',b,s);
        end
        local out_s = (string.format('sflash_send512_MSB 0x%s',s));
        proc_data_pos(dpos-1,true,out_s,s);
        dpos = dpos + 64;
    end
end

if(true)then
    while(dpos<=#outbin)do
        local b1 = outbin:byte(dpos);
        local b2 = outbin:byte(dpos+1) or 0;
        local b3 = outbin:byte(dpos+2) or 0;
        local b4 = outbin:byte(dpos+3) or 0;
        --print(dpos,b1,b2,b3,b4);
        local u32 = b1|(b2<<8)|(b3<<16)|(b4<<24);
        local out_s = string.format('sflash_send32 0x%08x',u32);

        local ddpos = dpos - 1;
        dpos = dpos + 4;

        proc_data_pos(ddpos,false,out_s,u32);
    end
end

print('sflash_program_end 0xffffffff');


